package com.example.client_group5;
import java.util.ArrayList;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.json.JSONArray;
import org.json.JSONObject;

import com.example.base.AppBaseActivity;

import eu.erikw.PullToRefreshListView;
import eu.erikw.PullToRefreshListView.OnRefreshListener;

import util.DateUtil;
import util.HttpClientFactory;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

public class ViewTweetUserActivity extends AppBaseActivity {
	int itemsPerPage = 6;
	boolean loadingMore = false;
	private ArrayList<Tweet> tweets;
	public static UserItemAdapter adapter;
	private int max_id = -1;
	private int since_id = -1;
	private String owner_id = "";
	private PullToRefreshListView listView;
	private View footerView;
	String[] infor;
	private ImageManager manager;
	private DateUtil dateUtil;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//				WindowManager.LayoutParams.FLAG_FULLSCREEN);
//		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.view_user_tweet);
        registerBaseActivityReceiver();
        Bundle b = getIntent().getExtras();
        infor = b.getStringArray("owner");
        owner_id = infor[0];
        
        listView = (PullToRefreshListView) findViewById(R.id.ListViewId);
        tweets = new ArrayList<Tweet>();
        dateUtil = new DateUtil();
        //manager = new ImageManager(getApplicationContext());
		manager = ImageManager.getInstance(getApplicationContext());
        adapter = new UserItemAdapter(this, R.layout.listitem, tweets);
       
        //add the footer before adding the adapter, else the footer will nod load!
        footerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listfooter, null, false);
        listView.addFooterView(footerView);
        
        listView.setAdapter(adapter);
        
        listView.setOnRefreshListener(new OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				
				Log.d("tag","loading first....");
				Thread thread=new Thread(null,loadFirstListItems);
				thread.start();	
			}
		});
        
       //Here is where the magic happens
        listView.setOnScrollListener(new OnScrollListener() {
			
        	//useless here, skip!
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				
			}
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				//what is the bottom item that is visible
				int lastInScreen = firstVisibleItem + visibleItemCount;				
				Log.d("tag", "lastInScreen: " + lastInScreen + "/ totalItemCount: " + totalItemCount);
				//is the bottom item visible & not loading more already ? Load more !
				if((lastInScreen == totalItemCount) && !(loadingMore)){
					Log.d("tag", "Loading more item...........");
					loadingMore=true;
					Thread thread =  new Thread(null, loadMoreListItems);
			        thread.start();
				}
			}
		});
        listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				if(arg2 >= 1){
					Tweet tweet = adapter.getItem(arg2 - 1);
					Log.d("content", tweet.content + " /arg2: " + arg2);	 
					Intent i = new Intent(ViewTweetUserActivity.this, TweetDetail.class);
					Bundle b = new Bundle();
					String[] info = {tweet.tweet_id, tweet.fullname, tweet.username, tweet.content, tweet.time, "" + tweet.isRetweeted, "" + tweet.isFavorite,
									tweet.retweetedUser, tweet.user_id, tweet.image_url, tweet.img_up_url, "", "" + (arg2 - 1)};
					b.putStringArray("tweet", info);
					i.putExtras(b);
					startActivity(i);
//					finish();
				}
			}
		});
        
        TextView textTweet = (TextView)findViewById(R.id.text_tweet_id);
        textTweet.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				Intent i = new Intent(getApplicationContext(), MainActivity.class);
//				startActivity(i);
//				finish();
				closeAllActivities();
			}
		});
        View tweetButton = (View)findViewById(R.id.btTweet);
        tweetButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(ViewTweetUserActivity.this, TweetActivity.class);
				Bundle b = new Bundle();
				String[] replyInfo = {"follow"};
				b.putStringArray("reply", replyInfo);
				i.putExtras(b);
				startActivity(i);
//				finish();
			}
		});
    }
    // Runnable to load first item
    private Runnable loadFirstListItems = new Runnable() {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			try{
				Thread.sleep(1000);
			}catch(InterruptedException e){
				e.printStackTrace();
			}
			tweets = new ArrayList<Tweet>();
			max_id=-1;
			since_id=Integer.parseInt(adapter.getItem(0).tweet_id);
	    	tweets = getTweets(owner_id, itemsPerPage, since_id, max_id);
	    	Log.d("tag", "size of first tweets: " + tweets.size());
	    	if(tweets.size() > 0){
	    		since_id= Integer.parseInt(tweets.get(0).tweet_id);
	    		Log.d("tag", "since id: " + since_id);
	    	}
			//Done! now continue on the UI thread
	        runOnUiThread(returnResult);
		}
	};
	//Since we cant update our UI from a thread this Runnable takes care of that! 
	private Runnable returnResult=new Runnable() {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			if(tweets!=null && tweets.size()>0)
			{
				for(int i=0;i<tweets.size();i++)
					adapter.insert(tweets.get(i), 0);
			}
			//Log.d("tag","since_id :"+since_id);
			adapter.notifyDataSetChanged();
			listView.onRefreshComplete();
			/*if(tweets.size() > 0)
				loadingHead=false;
			else
				listView.removeHeaderView(headerView);*/
		}
	};
	
	
    //Runnable to load the items 
    private Runnable loadMoreListItems = new Runnable() {			
		@Override
		public void run() {
			//Set flag so we cant load new items 2 at the same time
			//loadingMore = true;
	    	try{
	    		Thread.sleep(1000);
	    	}catch(InterruptedException e){}
	    	tweets = new ArrayList<Tweet>();
	    	tweets = getTweets(owner_id, itemsPerPage, since_id, max_id);
	    	Log.d("tag", "size of tweets: " + tweets.size());
	    	if(tweets.size() > 0){
	    		max_id = Integer.parseInt(tweets.get(tweets.size() - 1).tweet_id);
	    		Log.d("tag", "max id: " + max_id);
	    	}
			//Done! now continue on the UI thread
	        runOnUiThread(returnRes);
	        
		}
	};	
	//Since we cant update our UI from a thread this Runnable takes care of that! 
    private Runnable returnRes = new Runnable() {
        @Override
        public void run() {
        	if(tweets != null && tweets.size() > 0){
        		for(int i = 0; i < tweets.size(); i ++){
        			adapter.add(tweets.get(i));
        		}
        	}
        	Log.d("tag", "Adapter size: " + adapter.getCount());
        	//Update the Application title
        	setTitle("Neverending List with " + String.valueOf(adapter.getCount()) + " items");
        	//Tell to the adapter that changes have been made, this will cause the list to refresh
            adapter.notifyDataSetChanged();
			
			//Done loading more.
            if(tweets.size() > 0)
            	loadingMore = false;
            else
            	listView.removeFooterView(footerView);
        }
    };
    public ArrayList<Tweet> getTweets(String owner_id, int count, int since_id, int max_id){
    	String getUrl = "";
    	if(max_id == -1 && since_id == -1)
    		getUrl = Setting.ipServer + "api/tweet/user-timeline?user_id=" + owner_id + "&count=" + count;
    	else if(max_id != -1)
    		getUrl = Setting.ipServer + "api/tweet/user-timeline?user_id=" + owner_id + "&count=" + count + "&max_id=" + max_id;
    	else if(since_id != -1)
    		getUrl = Setting.ipServer + "api/tweet/user-timeline?user_id=" + owner_id + "&count=" + count + "&since_id=" + since_id;
		
		ArrayList<Tweet> tweets = new ArrayList<Tweet>();
		HttpClient client = HttpClientFactory.getThreadSafeClient();
		HttpGet get = new HttpGet(getUrl);
		 
		ResponseHandler<String> responseHandler = 
		        new BasicResponseHandler();

		String responseBody = null;
		try {
		    responseBody = client.execute(get, responseHandler);
		    
		} catch(Exception ex) {
			  ex.printStackTrace();
		}
		Log.d("tag", "Tra ve: " + responseBody);
		JSONObject jsonObject = null;
		
		
		try{
			jsonObject = new JSONObject(responseBody);
			Log.d("tag", jsonObject.toString());
			JSONArray jsonArray = jsonObject.getJSONArray("tweets");
			for(int i = 0; i < jsonArray.length(); i ++){
				JSONObject t = jsonArray.getJSONObject(i);
				String content = t.get("content").toString();
				String tweet_id = t.get("id").toString();
				String mention = t.get("mentions").toString();
				String time = t.get("created_time").toString();
				JSONObject author = t.getJSONObject("author");
				boolean isRetweeted = t.getBoolean("is_retweeted");
				boolean isFavorite = t.getBoolean("is_favorite");
				String retweetedUser = t.getString("retweeted_user");
				
				String user_id = author.get("id").toString();
				
				String username = author.get("username").toString();
				
				String fullname = author.get("fullname").toString();
				
				
				String profile_url = author.get("avatar").toString();
				Log.d("tag", "content / username / url: " + username + " / " + content + " / " + profile_url);
				Tweet tweet = new Tweet(tweet_id, fullname, username, user_id, mention, content,"", profile_url, time, isRetweeted, isFavorite, retweetedUser);
				tweets.add(tweet);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return tweets;
	}
    class UserItemAdapter extends ArrayAdapter<Tweet> {
		private ArrayList<Tweet> tweets;

		public UserItemAdapter(Context context, int textViewResourceId, ArrayList<Tweet> tweets) {
			super(context, textViewResourceId, tweets);
			this.tweets = tweets;
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.listitem, null);
			}
			Tweet tweet = tweets.get(position);
			if (tweet != null) {
				TextView fullname = (TextView)v.findViewById(R.id.fullname);
				TextView username = (TextView) v.findViewById(R.id.username);
				TextView mention = (TextView)v.findViewById(R.id.mention);
				TextView message = (TextView) v.findViewById(R.id.content);
				ImageView image = (ImageView) v.findViewById(R.id.avatar);
				ProgressBar progressBar = (ProgressBar)v.findViewById(R.id.progress_bar);
				ImageView icon = (ImageView) v.findViewById(R.id.icon_id);
				TextView time = (TextView)v.findViewById(R.id.time_id);
				if(fullname != null){
					fullname.setText(tweet.fullname);
				}
				if (username != null) {
					username.setText(tweet.username);
				}
				if(mention != null){
					mention.setText(tweet.mention);
				}

				if(message != null) {
					message.setText(tweet.content);
				}
				if(time != null){
					dateUtil.getDiffDate(tweet.time);
					if(dateUtil.getYear() != 0){
						time.setText(dateUtil.getYear() + "y");
					}
					else if(dateUtil.getMonth() != 0){
						time.setText(dateUtil.getYear() + "M");
					}
					else if(dateUtil.getDay() != 0){
						time.setText(dateUtil.getDay() + "d");
					}
					else if(dateUtil.getHour() != 0){
						time.setText(dateUtil.getHour() + "h");
					}
					else if(dateUtil.getMinute() != 0){
						time.setText(dateUtil.getMinute() + "m");
					}
					else if(dateUtil.getSecond() != 0){
						time.setText(dateUtil.getSecond() + "s");
					}
				}
				if(image != null) {
					image.setTag(tweet.image_url);	
					manager.displayImage(tweet.image_url, ViewTweetUserActivity.this, image, progressBar);
				}
				
				if(icon != null){
					if(tweet.isRetweeted && !tweet.isFavorite){
						icon.setBackgroundResource(R.drawable.retweet_icon);
						icon.setVisibility(View.VISIBLE);
					}
					if(!tweet.isRetweeted && tweet.isFavorite){
						icon.setBackgroundResource(R.drawable.favorite_icon1);
						icon.setVisibility(View.VISIBLE);
					}
					if(tweet.isRetweeted && tweet.isFavorite){
						icon.setBackgroundResource(R.drawable.favorite_retweet_icon);
						icon.setVisibility(View.VISIBLE);
					}
					if(!tweet.isRetweeted && !tweet.isFavorite){
						icon.setVisibility(View.GONE);
					}	
				}
			}
			return v;
		}
	}
	public boolean onKeyDown(int keycode, KeyEvent event){
		if(keycode == KeyEvent.KEYCODE_BACK){
			finish();
		}
    	return false;
    }
	public void onDestroy(){
		super.onDestroy();
		System.gc();
		unRegisterBaseActivityReceiver();
	}
	

    
}
